import {
  Controller,
  Get,
  Post,
  Body,
  Delete,
  UseInterceptors,
  UseGuards,
  NotFoundException,
  ClassSerializerInterceptor,
  Query,
  UploadedFile,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { FileService } from './file.service';
import { FileInterceptor } from '@nestjs/platform-express';

@ApiTags('文件')
@Controller('file')
export class FileController {
  constructor(
    private readonly filesService: FileService,
  ) {}

  @UseGuards(AuthGuard('jwt'))
  @UseInterceptors(ClassSerializerInterceptor)
  @ApiBearerAuth()
  @Get('list')
  findAll(@Query('current') current = 1, @Query('pageSize') pageSize = 10) {
    return this.filesService.findAll(+current, +pageSize);
  }

  validateFile = async (file: any) => {
    const isMax = file.size / 1024 / 1024 > 5;
    const mimetype = file.mimetype;
    if (!/(png|jpg|jpeg|gif|svg)$/.test(mimetype)) {
      throw new NotFoundException('文件格式有误');
    }
    if (isMax) {
      throw new NotFoundException('文件大小超出限制');
    }
  };

  @UseGuards(AuthGuard('jwt'))
  @UseInterceptors(ClassSerializerInterceptor)
  @ApiBearerAuth()
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file) {
    return await this.filesService.create(file);
  }

  /**
   * 删除图片
   */
  @UseGuards(AuthGuard('jwt'))
  @UseInterceptors(ClassSerializerInterceptor)
  @ApiBearerAuth()
  @Delete('remove')
  public async remove(@Body() body) {
    return this.filesService.remove(+body.id);
  }
}
